<template>
  <el-row>
    <el-col :span="22">
    </el-col>
    <el-col :span="2">
      <div class="condition-add">
        <el-button @click="handleAdd" type="primary">
          <i-ep-plus/>
          增加搜索条件
        </el-button>
      </div>
    </el-col>
  </el-row>
  <el-table
      ref="dataTableRef"
      :data="conditionList"
      border
  >
    <el-table-column label="列名">
      <template #default="scope">
        <el-select v-model="scope.row.fieldName" @change="handleFieldChange($event,scope.row,fields)" filterable>
          <el-option
              v-for="item in fields"
              :key="item.name"
              :label="item.label"
              :value="item.name"
          />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column label="比较" width="200">
      <template #default="scope">
        <el-select v-model="scope.row.operation">
          <el-option
              v-for="item in scope.row.operations"
              :key="item.name"
              :label="item.name"
              :value="item.value"
          />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column label="值">
      <template #default="scope">
        <el-input-number v-if="scope.row.type=='number'" v-model="scope.row.value"/>

        <el-date-picker style="width: 100%" v-else-if="scope.row.type=='date' && scope.row.operation != 'between'"
                        v-model="scope.row.value" type="date"
                        value-format="YYYY-MM-DD" placeholder="选择日期"/>
        <el-date-picker style="width: 100%" v-else-if="scope.row.type=='date' && scope.row.operation == 'between'"
                        v-model="scope.row.valueArr" type="daterange"
                        value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期"/>

        <el-date-picker style="width: 100%" v-else-if="scope.row.type=='datetime' && scope.row.operation != 'between'"
                        v-model="scope.row.value" type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期"/>
        <el-date-picker style="width: 100%" v-else-if="scope.row.type=='datetime' && scope.row.operation == 'between'"
                        v-model="scope.row.valueArr" type="datetimerange"
                        value-format="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期"/>

        <el-time-picker style="width: 100%" v-else-if="scope.row.type=='time' && scope.row.operation != 'between'"
                        v-model="scope.row.value"
                        value-format="HH:mm:ss" placeholder="选择时间"/>
        <el-time-picker style="width: 100%" v-else-if="scope.row.type=='time' && scope.row.operation == 'between'"
                        v-model="scope.row.valueArr"
                        value-format="HH:mm:ss" range-separator="至" start-placeholder="开始时间"
                        end-placeholder="结束时间"/>


        <el-select v-else-if="scope.row.type=='select' && scope.row.operation != 'in' " v-model="scope.row.value"
                   filterable>
          <el-option
              v-for="item in getOptionByName(scope.row.fieldName)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-select v-else-if="scope.row.type=='select' && scope.row.operation == 'in' " v-model="scope.row.valueArr"
                   multiple filterable>
          <el-option
              v-for="item in getOptionByName(scope.row.fieldName)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-input v-else v-model="scope.row.value"/>
      </template>
    </el-table-column>

    <el-table-column fixed="right" label="操作" width="80">
      <template #default="scope">
        <el-button
            type="danger"
            size="small"
            link
            @click="handleDelete(scope.row.id)"
        >
          <i-ep-delete/>
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-row>
    <el-col :span="18">
    </el-col>
    <el-col :span="6">
      <div class="dialog-footer condition-confirm">
        <el-button type="primary" @click="handleConfirm">
          <i-ep-search/>
          搜索
        </el-button>
        <el-button @click="handleCancel">
          <i-ep-close/>
          取消
        </el-button>
      </div>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">

import {deepCopy} from "@/utils/request";

/**
 * fields格式定义
 * name 字段名称
 * label 显示名称
 * type 类型：select date datetime time number input 可选 默认是input
 * options select 时，选项的值 ，格式为[{label:"xxx",value:"xxx"}]
 */
const props = defineProps({
  fields: {
    type: Array,
    required: true,
  },
});

function getOptionByName(name: any) {
  for (let i = 0; i < props.fields.length; i++) {
    const x = props.fields[i];
    if (x.name == name) {
      return x.options;
    }
  }
  return [];
}

const emits = defineEmits(["confirm", "cancel"]);

type conditionEntity = {
  id: number;
  //字段名称
  fieldName: string;
  //字段值
  value: string;
  //时间范围，数组
  valueArr: [];
  //比较类型
  operation: string;
}

const conditionList = ref<conditionEntity[]>([]);
const conditionLastList = ref<conditionEntity[]>([]);

const desensitizeOperations = ref([
  {name: "等于", value: "eq"},
  {name: "不等于", value: "ne"},
]);

const stringOperations = ref([
  {name: "包含", value: "like"},
  {name: "等于", value: "eq"},
  {name: "大于", value: "gt"},
  {name: "小于", value: "lt"},
  {name: "不等于", value: "ne"},
]);

const dateOperations = ref([
  {name: "等于", value: "eq"},
  {name: "之间", value: "between"},
  {name: "大于", value: "gt"},
  {name: "小于", value: "lt"},
  {name: "包含", value: "like"},
]);

const numberOperations = ref([
  {name: "等于", value: "eq"},
  {name: "大于", value: "gt"},
  {name: "大于等于", value: "ge"},
  {name: "小于", value: "lt"},
  {name: "小于等于", value: "le"},
]);

const selectOperations = ref([
  {name: "等于", value: "eq"},
  {name: "不等于", value: "ne"},
  {name: "包含", value: "in"},
]);


function handleAdd() {
  let id = Math.random();
  let entity: conditionEntity = {
    id: id,
    fieldName: '',
    value: '',
  };
  conditionList.value.push(entity);
}

function handleDelete(id: number) {
  let index = -1;
  for (let j = 0; j < conditionList.value.length; j++) {
    const x = conditionList.value[j];
    if (x.id == id) {
      index = j;
      break;
    }
  }
  if (index != -1) {
    conditionList.value.splice(index, 1);
  }
}

function handleFieldChange(value, condition, fields1) {
  var type = "string";
  fields1.forEach(x => {
    if (x.name == value) {
      type = x.type;
    }
  })
  if (type == "date" || type == "time" || type == "datetime") {
    condition.operations = dateOperations.value;
  } else if (type == "number") {
    condition.operations = numberOperations.value;
  } else if (type == "select") {
    condition.operations = selectOperations.value;
  } else if (type == "desensitize") {
    condition.operations = desensitizeOperations.value;
  } else {
    condition.operations = stringOperations.value;
  }
  condition.type = type;
  condition.value = '';
  condition.operation = '';
}

function handleConfirm() {
  var errMsg = '';
  conditionList.value.forEach(x => {
    if (x.fieldName == null || x.fieldName == '') {
      errMsg = '请选择列.';
      return;
    }
    if (x.valueArr && x.valueArr.length > 0) {
      x.value = x.valueArr.join(',');
    }
    if (x.value == null || x.value == '') {
      errMsg = '请选择比较列.';
      return;
    }
  });

  if (errMsg != '') {
    ElMessage.warning(errMsg);
    return;
  }


  conditionLastList.value = deepCopy(conditionList.value)
  emits("confirm", conditionList.value);
}

function handleCancel() {
  conditionList.value = deepCopy(conditionLastList.value)
  emits("cancel");
}

function resetMoreCondition() {
  conditionList.value = [];
  conditionLastList.value = [];
}

onBeforeMount(() => {
});
defineExpose({resetMoreCondition});
</script>

<style lang="scss" scoped>
.condition-add {
  margin-top: 10px;
  margin-bottom: 10px;
  float: right,
}

.condition-confirm {
  margin-top: 10px !important;
  margin-bottom: !important;
  float: right;
}
</style>
